package com.java.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author jingjintao
 * @date 2021/6/20 - 22:56
 **/
public class SessionServlet extends BaseServlet {


    protected void deleteNow(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        // 让Session会话马上超时
        session.invalidate();
        response.getWriter().write("Session已经设置为超时（无效）");
    }

    protected void life3(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置当前Session3秒后超时
        request.getSession().setMaxInactiveInterval(3);
        response.getWriter().write("当前Session已经设置为3秒后超时");
    }

    protected void defaultLife(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取了session的默认超市时长
        int maxInactiveInterval = request.getSession().getMaxInactiveInterval();
        response.getWriter().write("Session的默认超时时长为：" + maxInactiveInterval + " 秒 ");
    }
    /**
     * 往session中存入数据
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void setAttribute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().setAttribute("key1","value1");
        response.getWriter().write("已经往session中存入了数据");
    }

    /**
     * 从session域中获取数据
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void getAttribute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Object key1 = request.getSession().getAttribute("key1");
        response.getWriter().write("session域中数据的key1："+key1);
    }

    protected void createOrGetSession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建和获取session对象
        HttpSession session = request.getSession();
        //判断 当前session会话 是否是新创建出来的
        boolean isNew = session.isNew();
        //获取session会话的唯一表示
        String id = session.getId();

        response.getWriter().write("得到的session，它的Id是:"+id);
        response.getWriter().write("<br>这个session是否是新创建出来的:"+isNew);
    }
}
